﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Assets {
    /// <summary>
    /// HexString  <=> ByteArray
    /// </summary>
    class Hex {
        static char[] TABLE = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
        };
        public static String bytesToString(byte[] src) {
            int length = src.Length;
            int dstlength = length * 2;
            char[] buf = new char[dstlength];

            for(int i = 0; i < length; i++) {
                buf[i * 2] = TABLE[(src[i] & 0xFF) >> 4];//H
                buf[i * 2 + 1] = TABLE[((src[i] & 0x0F)) & 0xFF];//L

            }
            return new String(buf, 0, dstlength);
        }
        public static void stringToBytes(String src, byte[] outArray) {
            if(outArray.Length * 2 < src.Length) {
                throw new Exception("out.length*2<src.length()");
            }
            char[] chars = src.ToCharArray();
            for(int i = 0; i < outArray.Length; i++) {
                int h = 0;
                int l = 0;
                for(int j = 0; j < TABLE.Length; j++) {
                    if(chars[i * 2] == TABLE[j]) { h = j; break; }
                }
                for(int j = 0; j < TABLE.Length; j++) {
                    if(chars[i * 2 + 1] == TABLE[j]) { l = j; break; }
                }
                outArray[i] = (byte)((((h << 4 | l & 0x0F))) & 0xFF);
            }
        }
    }
}
